//
//  VideoClassfilyViewController.m
//  SuperNews
//
//  Created by qiang on 16/1/14.
//  Copyright © 2016年 qiang. All rights reserved.
//

#import "VideoClassfilyViewController.h"
#import "VideoPageModel.h"
#import "VideoTableViewCell.h"

@interface VideoClassfilyViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, weak) UITableView *tableview;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) AVPlayerViewController *player;
@property (nonatomic, assign) CGRect firstRect;
@property (nonatomic, assign) int currtRow;
@property (nonatomic, assign) BOOL smallplayer;
@property (nonatomic, assign) BOOL finsh;
@property (nonatomic, weak) UIButton *stopBut;

@end

@implementation VideoClassfilyViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    for (UIView * view in self.navigationController.navigationBar.subviews) {
        if ([view isKindOfClass:[UISegmentedControl class]]) {
            view.hidden = YES;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    for (UIView * view in self.navigationController.navigationBar.subviews) {
        if ([view isKindOfClass:[UISegmentedControl class]]) {
            view.hidden = NO;
        }
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.player) {
        [self.player.player pause];
        [self.player.view removeFromSuperview];
        self.player = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self createSubviews];
    [self setupRefreshView];
    
}
- (void)createSubviews
{
    UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 70) style:UITableViewStylePlain];
    tableview.backgroundColor = [UIColor clearColor];
    tableview.delegate = self;
    tableview.dataSource = self;
    [self.view addSubview:tableview];
    self.tableview = tableview;
}

- (void)setupRefreshView
{
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableview.mj_header beginRefreshing];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadNewData
{
    self.count = 0;
    [self getData];
    
}
- (void)loadMoreData
{
    [self getData];
}

- (void)getData
{
     NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/video/list/%@/y/%ld-10.html", self.url, self.count];
     [AFNetTool getNetWithURL:url body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
         if (0 == self.videoArray.count) {
             self.videoArray = [VideoPageModel baseModelWithArr:responseObject[self.url]];
         } else {
             for (NSMutableDictionary *dic in responseObject[self.url]) {
                 VideoPageModel *video = [VideoPageModel baseModelWithDic:dic];
                 [self.videoArray addObject:video];
             }
         }
         self.count += 10;
         // 刷新表格
         [self.tableview.mj_header endRefreshing];
         [self.tableview.mj_footer endRefreshing];
         [self.tableview reloadData];
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         
         
     }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoPageModel *videodata = self.videoArray[indexPath.row];
    
    if (self.player) {
        [self.player.view removeFromSuperview];
    }
    self.finsh = NO;
    self.smallplayer = NO;
    self.currtRow = (int)indexPath.row;
    // 创建播放器对象
    AVPlayerItem *playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:videodata.mp4_url]];
    self.player = [[AVPlayerViewController alloc] init];
    AVPlayer *py = [AVPlayer playerWithPlayerItem:playItem];
    self.player.player = py;
    // 添加播放器界面到控制器的view上面
    self.player.view.frame = CGRectMake(10, indexPath.row * 300 + 50, SCREEN_WIDTH - 20, 200);
    [self.tableview addSubview:self.player.view];
    
    // 监听播放器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDidFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:playItem];
    [py play];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoTableViewCell *cell = [VideoTableViewCell cellWithTableView:tableView];
    cell.videodata = self.videoArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 从锚点位置出发，逆时针绕 Y 和 Z 坐标轴旋转90度
    CATransform3D transform3D = CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 1.0);
    
    // 定义 cell 的初始状态
    cell.alpha = 0.0;
    cell.layer.transform = transform3D;
    cell.layer.anchorPoint = CGPointMake(0.0, 0.5); // 设置锚点位置；默认为中心点(0.5, 0.5)
    
    [UIView animateWithDuration:0.5 animations:^{
        cell.alpha = 1.0;
        cell.layer.transform = CATransform3DIdentity;
        CGRect rect = cell.frame;
        rect.origin.x = 0.0;
        cell.frame = rect;
    }];
}

- (void)movieDidFinish
{
    UIView *vc = [[UIView alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 40, self.player.view.frame.size.height)];
    UILabel *l =[[UILabel alloc] initWithFrame:CGRectMake(10, 70, SCREEN_WIDTH - 40, 40)];
    l.text = @"播放完毕";
    l.font = [UIFont boldSystemFontOfSize:13];
    l.textColor = [UIColor whiteColor];
    l.textAlignment = NSTextAlignmentCenter;
    [vc addSubview:l];
    vc.backgroundColor = [UIColor blackColor];
    self.player.showsPlaybackControls = NO;
    
    [self.player.view addSubview:vc];
    if (YES == self.smallplayer) {
        l.frame = CGRectMake(0, 40, self.player.view.frame.size.width - 20, 30);
        l.font = [UIFont boldSystemFontOfSize:13];
    }
    self.finsh = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.player && NO == self.smallplayer && NO == self.finsh) {
        
        if (fabs(scrollView.contentOffset.y) > CGRectGetMaxY(self.player.view.frame)) {
            self.firstRect = self.player.view.frame;
            self.smallplayer = YES;
            self.player.view.frame = CGRectMake(SCREEN_WIDTH - 200, SCREEN_HEIGHT - 220, 200, 200*0.56);
            self.player.showsPlaybackControls = NO;
            
            UIButton *stopBut = [UIButton buttonWithType:UIButtonTypeCustom];
            stopBut.frame = CGRectMake(0, 0, 20, 20);
            [stopBut setImage:[UIImage imageNamed:@"recommendlist_cell_close"] forState:UIControlStateNormal];
            [stopBut addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.player.view addSubview:stopBut];
            self.stopBut = stopBut;
            [self.view addSubview:self.player.view];
        }
    }
    if (self.player && YES == self.smallplayer) {
        if (fabs(scrollView.contentOffset.y) < self.firstRect.origin.y + self.firstRect.size.height) {
            self.smallplayer = NO;
            self.player.view.frame = self.firstRect;
            self.player.showsPlaybackControls = YES;
            [self.tableview addSubview:self.player.view];
            [self.stopBut removeFromSuperview];
        }
    }
}

- (void)stopAction:(id)sender
{
    [self.player.player pause];
    [self.player.view removeFromSuperview];
    self.player = nil;
    [self.tableview reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
